package com.example.sentineldemo.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.example.sentineldemo.handler.CommonBackHandler;
import com.example.sentineldemo.handler.ResourceKey;
import org.springframework.stereotype.Component;

/**
 * @author wangjinlong
 * @date 2022/2/11 9:26
 */
@Component
public class StoreQueryService {

    @SentinelResource(
            value = ResourceKey.KEY_STORE,
            blockHandlerClass = CommonBackHandler.class, blockHandler = "handleBlockException",
            fallbackClass = CommonBackHandler.class, fallback = "handleAllException"
    )
    public String queryStoreInfo(String storeId) {
        int i = 10 / 0;
        return "store - " + storeId;
    }

    /*@PostConstruct
    public void initFlowQpsRule() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule1 = new FlowRule();
        rule1.setResource(ResourceKey.KEY_STORE);
        // QPS控制在1以内
        rule1.setCount(1);
        // QPS限流
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule1.setLimitApp("default");
        rules.add(rule1);
        FlowRuleManager.loadRules(rules);
    }

    @PostConstruct
    public void initDegradeRule() {
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        rule.setResource(ResourceKey.KEY_STORE);
        // 10s内调用接口出现异常次数超过5的时候, 进行熔断
        rule.setCount(5);
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
        rule.setTimeWindow(10);
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }*/
}
